package edu.xidian.bdilab.jrbigdata.Interceptor;

import edu.xidian.bdilab.jrbigdata.controller.response.MetaData;
import edu.xidian.bdilab.jrbigdata.controller.response.ResponseResult;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author zhangmin
 * @create 2021-05-13 14:05
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)throws Exception
    {
        HttpSession session=request.getSession();
//        System.out.println("\n现在经过preHandle:**********");
//        System.out.println("preHandle:    HttpServletRequest= "+request.toString());
//        System.out.println("preHandle:    user= "+session.getAttribute("user_name"));
//        System.out.println("preHandle:    sessionId= "+session.getId());
        if(session.getAttribute("user_name")==null)
        {
            response.setStatus(401);
            ResponseResult responseResult = new ResponseResult();
            responseResult.setMeta(new MetaData(true,"401","登录过期，请重新登录"));
            response.getWriter().print(responseResult.getMeta().toString());
            response.sendRedirect("index.html");
            return false;
        }
//        System.out.println("preHandle:     即将返回true  user="+session.getAttribute("user_name"));
        return  true;
    }
    /**
     * 生成视图时执行，可以用来处理异常，并记录在日志中
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object arg2, Exception exception){
//        System.out.println("经过aftercompletion");
    }

    /** -
     * 生成视图之前执行，可以修改ModelAndView
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object arg2, ModelAndView arg3)
            throws Exception{
//        System.out.println("经过posthandle");
    }
}
